package com.example.chesswithnet.Controller;

import com.example.chesswithnet.Entity.Chess;
import com.example.chesswithnet.Entity.MoveRecord;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.geometry.Point2D;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;

import java.util.*;

public class chessController extends BaseController{

    @FXML
    Canvas canvas;
    @FXML
    Label lHint;
    @FXML
    Button btnRestart;
    @FXML
    Button btnBackMove;
    Chess selectChess = null;
    Map<Point2D, Chess> map = new HashMap();
    List<MoveRecord> moveRecord = new ArrayList<>();  //移动记录
    private GraphicsContext gc;
    Alert alert = new Alert(Alert.AlertType.INFORMATION);
    String[] s = {"che","ma","xiang","shi","boss","shi","xiang","ma","che","bing","pao","bing","bing","bing","pao", "bing"};
    //红棋位置
    Point2D[] point2D = {
            new Point2D(0,0),new Point2D(1,0),new Point2D(2,0),new Point2D(3,0),new Point2D(4,0),
            new Point2D(5,0),new Point2D(6,0),new Point2D(7,0),new Point2D(8,0), new Point2D(0,3),
            new Point2D(1,2),new Point2D(2,3),new Point2D(4,3),new Point2D(6,3), new Point2D(7,2),
            new Point2D(8,3)
    };
    Map<Integer,Chess> bossMap = new HashMap<>();
//    public enum SortChess{
//        Red_Chess,
//        Black_Chess
//    }
//    SortChess sortChess = chessController.SortChess.Red_Chess;
    boolean sortChess = true; // true:红棋下棋 false:黑棋下棋

    /**
     * 初始化
     */
    public void initialize(){
        gc = canvas.getGraphicsContext2D();
        chessBg();
        setMap();
        drawChessAll();
        //鼠标点击事件
        canvas.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                Point2D point2D = getPointFromXY(event.getSceneX(),event.getSceneY());
                //移动棋子
                Chess c = (Chess) map.get(point2D);
                selectChess(c,point2D);
            }
        });
        //重新开始按钮点击事件
        btnRestart.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                alert.setAlertType(Alert.AlertType.CONFIRMATION);
                alert.setContentText("确定要重新开始吗？");
                Optional<ButtonType> buttonType = alert.showAndWait();
                Restart(buttonType);
            }
        });
        //悔棋按钮点击事件
        btnBackMove.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                HuiQi();
            }
        });

    }

    /**
     * 重新开始
     */
    public void Restart(Optional<ButtonType> buttonType){
        //点击确定按钮
        if(buttonType.get().getButtonData().isDefaultButton()){
            selectChess = null;
            sortChess = true;
            map.clear();
            setHint();
            clear();
            chessBg();
            setMap();
            drawChessAll();
        }
    }

    /**
     * 将军不能面对面
     * @return
     */
    public boolean FacetoFaceJiang(){
        Chess shuai = bossMap.get(0);
        Chess jiang = bossMap.get(1);
        int i = 0,count = 0;
        if(shuai.getP().getX() == jiang.getP().getX()){
            for (Point2D entry : map.keySet())
                if (map.get(new Point2D(shuai.getP().getX(),i++)) != null) count++;
            System.out.println(count);
            if(count - 2 == 0) return true;
        }
        System.out.println(count);
        return false;
    }

    /**
     * 游戏结束
     * @param name
     */
    public void EndGame(String name){
        alert.setAlertType(Alert.AlertType.INFORMATION);
        alert.setContentText("游戏结束，"+name+"胜利，点击确定按钮重新开始游戏");
        Optional<ButtonType> buttonType = alert.showAndWait();
        Restart(buttonType);
    }

    /**
     * 选中棋子移动
     */
    public void selectChess(Chess c,Point2D point2D){
        if(selectChess == null) {
            //第一选中
            if (c != null) {
                if (sortChess && c.getPlayer() == 0 || !sortChess && c.getPlayer() == 1)
                    selectChess = c;
                else {
                    alert.setContentText("不能选择对方的棋子");
                    alert.showAndWait();
                }
            }
        } else { //移动
            if(c == null){   //选择的位置里没有其他棋子，就移动
                if(selectChess.isAbleMoved(point2D,map)) {
                    //复制selectChess棋子
                    Chess chess = new Chess(selectChess.getUrl(),selectChess.getX(),selectChess.getY(),selectChess.getP(),selectChess.getPlayer());
//                    if(FacetoFaceJiang()) {
//                        alert.setAlertType(Alert.AlertType.INFORMATION);
//                        alert.setContentText("将帅之间不能没有棋子");
//                        alert.showAndWait();
//                        return;
//                    }
                    moveRecord.add(new MoveRecord(chess,point2D));  //添加移动记录
                    moveChess(selectChess, point2D);
                    setHint();
                }else return;
            }else//选择的位置有其他棋子
                //第一次选中的棋子跟第二次选中的棋子不是同一个颜色的就吃子
                if (c.getPlayer() != selectChess.getPlayer()) {
                    if (selectChess.isAbleMoved(point2D, map) && selectChess.eatChess(point2D,map)){
                        //复制selectChess棋子
                        Chess chess = new Chess(selectChess.getUrl(),selectChess.getX(),selectChess.getY(),selectChess.getP(),selectChess.getPlayer());
                        moveRecord.add(new MoveRecord(chess,point2D,c));  //添加移动记录 c是被吃的棋子
                        isJiangjun(c);
//                        if(FacetoFaceJiang()) {
//                            alert.setAlertType(Alert.AlertType.INFORMATION);
//                            alert.setContentText("将帅之间不能没有棋子");
//                            alert.showAndWait();
//                            return;
//                        }
                        moveChess(selectChess, point2D);
                        setHint();
                    }
                }else  //第一次选中的棋子跟第二次选中的棋子是同一个颜色的就重新选择
                    selectChess = c;
        }
        refresh();
    }

    /**
     * 悔棋
     */
    public void HuiQi(){
        alert.setAlertType(Alert.AlertType.CONFIRMATION);
        alert.setContentText("确定要悔棋吗？");
        Optional<ButtonType> buttonType = alert.showAndWait();
        if (buttonType.get().getButtonData().isDefaultButton()) {
            //历史记录没有数据就退出
            if (moveRecord.isEmpty()) return;
            MoveRecord chess1 = moveRecord.get(moveRecord.size() - 1);  //移动记录的最新一条记录，也就是要悔的棋子
//        System.out.println(Arrays.asList(moveRecord));
            Chess chess2 = map.get(chess1.getPoint2D());  //map里要悔的棋子现在的位置
            if (chess2 != null)
                map.remove(chess2.getP());
            if (chess1.getChess1() != null)
                map.put(chess1.getChess1().getP(), chess1.getChess1());
            map.put(chess1.getChess().getP(), chess1.getChess());
            System.out.println(chess1.getChess().getY());
            gc.strokeRect(chess1.getChess().getX(),chess1.getChess().getY(),30,30); //设置后退的棋子选中框
            selectChess = chess1.getChess();  //当前选中的棋子变成悔棋的棋子
            setHint();
            refresh();
            moveRecord.remove(moveRecord.size() - 1);
        }
        return;

    }

    /**
     * 判断吃掉的是否将军 是的话结束游戏
     * @param chess
     */
    public void isJiangjun(Chess chess){
        if(chess.getUrl() == "boss")
            if(chess.getPlayer() == 0) {
                System.out.println("黑棋胜利");
                EndGame("黑棋");
            }
            else {
                System.out.println("红棋胜利");
                EndGame("红棋");
            }
        return;
    }

    /**
     * 交换下棋
     *    +
     * 设置下棋提示信息
     */
    public void setHint(){
        sortChess = !sortChess;  //交换下棋
        if (sortChess) {
            lHint.setText("红棋走");
        } else {
            lHint.setText("黑棋走");
        }
    }


    /**
     * 移动棋子
     */
    public void moveChess(Chess selectChess, Point2D point2D) {
        map.remove(selectChess.getP());
        selectChess.setPointXY(point2D, 5 + 40 * point2D.getX(), 5 + 40 * point2D.getY());
        map.put(point2D, selectChess);
        this.selectChess = null;    //移动完成后清空选中
    }

    /**
     * 获取棋子坐标
     */
    public Point2D getPointFromXY(Double x, Double y){
        return new Point2D((int)(x-5)/40,(int)(y-5)/40);
    }

    /**
     * 绘制所有棋子
     */
    public void drawChessAll(){
        for (Object point2D : map.keySet()){
            Chess chess = (Chess) map.get(point2D);
            chess.draw(gc);
        }
    }

    /**
     * 给map赋值
     */
    public void setMap(){

        /**创建红棋 **/
        for (int i = 0;i<s.length;i++){
            Double x = 5 + 40 * point2D[i].getX();
            Double y = 5 + 40 * point2D[i].getY();
            Chess c = new Chess(s[i],x,y,point2D[i],0);
            map.put(c.getP(),c);
            if(c.getUrl() == "boss") bossMap.put(0,c);
        }
        /** 创建黑棋 **/
        for (int i = 0;i<s.length;i++){
            Chess c = new Chess(s[i],point2D[i],1);
            c.reservePoint();
            map.put(c.getP(),c);
            if(c.getUrl() == "boss") bossMap.put(1,c);
        }
    }


    /**
     * 创建棋子背景
     */
    public void chessBg(){
        Image image = new Image(String.valueOf(getClass().getResource("../img1/qipan.jpg")));
        gc.drawImage(image,0,0);
    }

    /**
     * 刷新
     */
    public void refresh(){
        clear();
        chessBg();
        drawChessAll();
        if (selectChess != null)
            gc.strokeRect(selectChess.getX(),selectChess.getY(),30,30);
    }

    /**
     * 清空
     */
    public void clear(){
        gc.clearRect(0,0,canvas.getWidth(),canvas.getHeight());
    }

}
